<template>
  <div id="system-administrator">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <!-- 查询开始 -->
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="margin-top:20px"
          >
            <el-form-item>
              <el-input
                v-model="formInline.username"
                placeholder="输入管理员"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit()"
                icon="el-icon-search"
                clearable
                 v-permission="'admin:admin:list'"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(1)"
                v-permission="'admin:admin:create'"
                >添加</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 查询结束 -->
        </el-header>

        <el-main>
          <el-table
            :data="admintableData"
            style="width: 100%;"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
          >
            <!-- 列表数据 -->
            <el-table-column prop="id" label="管理员ID" sortable>
            </el-table-column>
            <el-table-column prop="username" label="管理员名称">
            </el-table-column>
            <el-table-column prop="desc" label="管理员头像"> </el-table-column>
            <el-table-column :data="admintableData.roleIds" label="管理员角色">
              <template slot-scope="scope">
                <el-tag v-for="item in scope.row.roleIds" :key="item">
                  {{
                    roletableData.find((items) => items.id == item)
                      ? roletableData.find((items) => items.id == item).name
                      : item
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(2, scope.$index, scope.row)"
                  v-permission="'admin:admin:updata'"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-permission="'admin:admin:delete'"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <!-- 底部页数 -->
          <paging :paging="paging" :onSubmit="onSubmit"></paging>
        </el-footer>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible" center>
      <!-- 对话框表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="width:85%"
      >
        <el-form-item label="登录名" prop="username">
          <el-input v-model="ruleForm.username" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="ruleForm.realname"></el-input>
        </el-form-item>
        <el-form-item label="授权角色">
          <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
            <el-option
              v-for="item in roletableData"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 对话框表单结束 -->
    </el-dialog>
  </div>
</template>

<script>
import admin from "@/api/admin";
import role from "@/api/role";
import Paging from "../../components/Paging";
export default {
  components: {
    Paging,
  },
  data() {
    var validateRole = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("管理员名称不能为空"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else {
        let number = /[0-9]{6,18}$/;
        if (number.test(value)) {
          callback();
        } else {
          callback(new Error("请输入6~18位数字或字符串"));
        }
      }
    };
    var cellphoneNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号码不能为空"));
      } else {
        let password = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (password.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号码"));
        }
      }
    };
    var realName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("真实姓名不能为空"));
      } else {
        let number = /^[\u4E00-\u9FA5]+$/;
        if (number.test(value)) {
          callback();
        } else {
          callback(new Error("请输入中文"));
        }
      }
    };
    return {
      formInline: {
        username: "", //管理员查询
      },
      ruleForm: {
        //表单数据
        username: "",
        password: "",
        phone: "",
        realname: "",
        roleIds: [], //添加的角色
      },
      roledata: "", //选中的数据
      index: "", //选中的下标
      rules: {
        //表单验证
        username: [
          { required: true, validator: validateRole, trigger: "blur" },
        ],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        phone: [
          { required: true, validator: cellphoneNumber, trigger: "blur" },
        ],
        realname: [{ required: true, validator: realName, trigger: "blur" }],
      },
      title: "创造", //对话框的名字
      dialogFormVisible: false, //对话框表单的隐藏显示
      admintableData: [], //后台全部管理员列表数据
      roletableData: [], //后台全部角色列表数据
      disabled: false, //禁用
      paging: {
        currentPage: 1, //出现的页数
        pagesize: 10, //    每页的数据
        total: 0, //总条数
      },
      rodetotal: 20, //角色总条数
    };
  },
  created: function() {
    //一开始的渲染数据
    this.onSubmit();
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      if (that.formInline.username!="") {//具体查询回到第一页，不然查询的数据在第一页，显示的页数和查询是页数不对
        that.paging.currentPage=1
      }
      let data = Object.assign({ page: that.paging.currentPage,limit: that.paging.pagesize,}, that.formInline)
      admin.adminInquire(
        //管理员查询接口封装
        data
       )
        .then((res) => {
          that.admintableData = res.data.data.items; //管理员获取数据赋值
          that.paging.total = res.data.data.total; //管理员总条数
          role.roleInquire({
            //角色查询接口封装
            page: 1,
            limit: that.rodetotal,
          }).then((res) => {
            that.roletableData = res.data.data.items; //角色获取数据赋值
            that.rodetotal = res.data.data.total; //角色总条数
          });
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleEdit(digit, index, row) {
      //编辑和添加
      console.log(row, index);
      let that = this;
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
      if (digit == 1) {
        this.disabled = false;
        this.title = "创造";
        for (const i in that.ruleForm) {
            that.ruleForm[i] = "";
          }
      } else {
          //防止重置时没有数据
          setTimeout(function() {
          that.disabled = true;
          that.title = "编辑";
          that.roledata = row;
          that.index = index;
          for (const i in that.ruleForm) {
            that.ruleForm[i] = row[i];
          }
          that.ruleForm.password = "";
          }, 50);
      }
    },
    submitForm(formName) {
      //提交
      let that = this;
      // console.log()
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          if (that.title == "创造") {
            //添加
            that.addition();
          } else {
            //编辑
            that.compile();
          }
        } else {
          return false;
        }
      });
    },
    addition() {
      //添加
      console.log(this.ruleForm);
      let that = this;
      admin.adminAddition({
        //添加封装接口
        adminDTO: JSON.stringify(that.ruleForm),
      }).then(function(res) {
        console.log(res);
        if (res.data.errmsg == "成功") {
          that.$message({
            type: "success",
            message: res.data.errmsg,
          });
          that.paging.total = that.paging.total + 1; //总共条数+1条
          that.onSubmit()
          that.admintableData.unshift(res.data.data);
        } else {
          that.$message({
            message: res.data.errmsg,
            type: "warning",
          });
        }
      });
    },
    compile() {
      //编制
      let that = this;
      let data = Object.assign(that.ruleForm,{id: that.roledata.id})
      admin.adminCompile({
        //编制封装接口
        adminDTO: JSON.stringify(data),
      }).then(function(res) {
        if (res.data.errmsg == "成功") {
          that.$message({
            type: "success",
            message: res.data.errmsg,
          });
           that.admintableData[that.index] = Object.assign( that.admintableData[that.index],that.ruleForm)
        } else {
          that.$message({
            message: res.data.errmsg,
            type: "warning",
          });
        }
      });
    },
    resetForm(formName) {
      //重置验证
      let that = this;
      setTimeout(function() {
        that.$refs[formName].resetFields();
      }, 50);
    },
    handleDelete(index, row) {
      //删除
      let that = this;
      this.$confirm("此操作将永久删除--"+row.username+"--, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          admin.adminDelete({
            //删除封装接口
            id: row.id,
          }).then(function(res) {
            if (res.data.errmsg == "成功") {
              that.$message({
                type: "success",
                message: res.data.errmsg,
              });
              that.paging.total = that.paging.total - 1; //总共条数-1条
              that.admintableData.splice(index, 1);
            } else {
              that.$message({
                showClose: true,
                message: res.data.errmsg,
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#system-administrator {
  //内容填满
  height: 100%;
}
.el-main {
  line-height: 0px !important;
}
.el-tag {
  margin-right: 20px;
}
.concer-input {
  //查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
</style>
